package LeetCode._01_树;

public class _1008_前序遍历构造二叉搜索树 {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
     }

    public TreeNode bstFromPreorder(int[] preorder) {
        if(preorder == null || preorder.length == 0) return null;
        return build(preorder,0,preorder.length-1);
    }

    private TreeNode build(int[] preorder,int preStart,int preEnd){
        if(preStart>preEnd) return null;

        int rootVal = preorder[preStart]; //根节点的值，在前序遍历的第一个
        TreeNode root = new TreeNode(rootVal); //构造根节点
        int left = preStart + 1; //找到左子树区间的值
        //可能整棵树都是左子树,左子树的值都比根节点的值要小
        while(left <= preEnd && preorder[left] < rootVal){
            left++;
        }
        //左子树的区间为[preStart+1,left-1]
        root.left = build(preorder,preStart+1,left-1);
        //右子树的区间为[left,preEnd]
        root.right = build(preorder,left,preEnd);

        return root;
    }
}
